package com.treetao.union.web.controller.system;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.treetao.union.core.exception.DevMException;
import com.treetao.union.core.util.FileUploadService;
import com.treetao.union.core.util.ToolUtil;
import com.treetao.union.db.SettingConvertService;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.pojo.SettingTypeSystem;
import com.treetao.union.web.controller.BaseAdminController;

import sun.net.www.protocol.http.HttpURLConnection;

/**
 * 文件上传
 */
@Controller
@RequestMapping("file")
public class SysFileController extends BaseAdminController{
	
	@Autowired
	private SettingConvertService settingConvertService;
	
	@Autowired
	private FileUploadService fileUploadService;
    
    @PostMapping("upload")
    @ResponseBody
    public RestResponse uploadFile(HttpServletRequest request,@RequestParam("test") MultipartFile file) {
        if(file == null){
            return RestResponse.failure("上传文件为空 ");
        }
        
        SettingTypeSystem system = settingConvertService.getSystemSetting();
        if(system==null) {
        	 return RestResponse.failure("请先进行配置 ");
        }
        
        Map<String,String> m = Maps.newHashMap();
        try {
			String url = fileUploadService.upload(file,system.getSystemSavePath(),system.getSystemPrefix());
			m.put("url", url);
            m.put("name", file.getOriginalFilename());
        } catch (DevMException e) {
        	return RestResponse.failure(e.getMessage());
		} catch (Exception e) {
            e.printStackTrace();
            return RestResponse.failure(e.getMessage());
        }
        return RestResponse.success().setData(m);
    }


    /**
     * wangEditor批量上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("uploadWang")
    @ResponseBody
    public Map<String,Object> uploadWang(@RequestParam("test") MultipartFile[] file) {
        if(file == null || file.length == 0){
            return RestResponse.failure("上传文件为空 ");
        }
        SettingTypeSystem system = settingConvertService.getSystemSetting();
        if(system==null) {
        	 return RestResponse.failure("请先进行配置 ");
        }
        List<String> data = Lists.newArrayList();
        Map<String,Object> m = Maps.newHashMap();
        try {
            for (int i=0;i<file.length;i++) {
            	String url = fileUploadService.upload(file[i],system.getSystemSavePath(),system.getSystemPrefix());
                data.add(url);
            }
            m.put("errno",0);
        } catch (Exception e) {
            e.printStackTrace();
            m.put("errno",1);
        }
        m.put("data",data);
        return m;
    }

    /**
     * wangEditor复制新闻中包含图片的话吧图片上传到七牛上并更换图片地址
     * @return
     */
    @PostMapping("doContent")
    @ResponseBody
    public RestResponse doContent(@RequestParam(value="content",required = false) String content) throws IOException, NoSuchAlgorithmException {
        if (StringUtils.isBlank(content)){
            return RestResponse.failure("复制内容为空");
        }
        SettingTypeSystem system = settingConvertService.getSystemSetting();
        if(system==null) {
        	 return RestResponse.failure("请先进行配置 ");
        }
        Document doc = Jsoup.parseBodyFragment(content);
        Elements links = doc.select("img[src]");
        for(Element e : links){
            String imgSrc = e.attr("abs:src");
            if(imgSrc.contains("file:")){
            	imgSrc = imgSrc.replace("\\","/");
                e.attr("src",fileUploadService.uploadNetFile(imgSrc.substring(6),system.getSystemSavePath(),system.getSystemPrefix()));
            }else{
            	 String url = fileUploadService.uploadNetFile(imgSrc,system.getSystemSavePath(),system.getSystemPrefix());
                e.attr("src",url);
            }
        }
        String outHtml = doc.body().toString();
        return RestResponse.success().setData(outHtml.replace("<body>","").replace("</body>",""));
    }

    @PostMapping("downCheck")
    @ResponseBody
    public RestResponse downCheck(@RequestParam(value="url",required = false) String url,
                                  @RequestParam(value="name",required = false) String name){
        if(StringUtils.isBlank(url)){
            return RestResponse.failure("图片地址不能为空");
        }
        if(StringUtils.isBlank(name)){
            return RestResponse.failure("图片名称不能为空");
        }
        return RestResponse.success();
    }

    @GetMapping("download")
    @ResponseBody
    public RestResponse downFile(@RequestParam(value="url",required = false) String realurl,
                                 @RequestParam(value="name",required = false) String name,
                                 HttpServletResponse response) throws IOException {
        if(StringUtils.isBlank(realurl)){
            return RestResponse.failure("图片地址不能为空");
        }
        if(StringUtils.isBlank(name)){
            return RestResponse.failure("图片名称不能为空");
        }
        if("text/html".equals(ToolUtil.getContentType(name))){
            return RestResponse.failure("图片格式不正确");
        }
        name = new String(name.getBytes("GB2312"),"ISO8859-1");
        URL url=new URL(realurl);
        HttpURLConnection conn=(HttpURLConnection)url.openConnection();
        conn.connect();
        BufferedInputStream br = new BufferedInputStream(conn.getInputStream());
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset();
        response.setHeader("Content-type","application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename="+name);
        ServletOutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) out.write(buf, 0, len);
        br.close();
        out.flush();
        out.close();
        conn.disconnect();
        return RestResponse.success();
    }
}
